package com.yu8home.opcua.test;

import com.yu8home.opcua.OpcUAUtil;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue;
import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
import org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Slf4j
public class WriteFor {

    public static void main(String[] args) throws Exception {
        OpcUAUtil.getConnect();

        long x = System.currentTimeMillis();
        List<OpcUABO> rows = new ArrayList<>();

        for (int i = 0; i < 9; i++) {
            OpcUABO a = new OpcUABO();
            a.setMarkName("aaaa.1.温度偏高报警值");
            a.setRawDataType("Word");
            a.setValue(String.valueOf(290 + i));
            rows.add(a);
        }
        writes(rows);
        log.info("readNode耗时：{}", System.currentTimeMillis() - x);
    }

    /**
     * 批量-写
     */
    public static void writes(List<OpcUABO> rows) {
        long x = System.currentTimeMillis();

        List<NodeId> nodeIds = new ArrayList<>();
        List<DataValue> values = new ArrayList<>();

        for (OpcUABO t : rows) {
            String markName = t.getMarkName();

            NodeId nodeId = new NodeId(2, markName);
            DataValue newValue = OpcUAUtil.getDataValue(t.getRawDataType(), t.getValue());

            nodeIds.add(nodeId);
            values.add(newValue);
        }

        CompletableFuture<List<StatusCode>> listCompletableFuture = OpcUAUtil.opcUaClient.writeValues(nodeIds, values);
        List<StatusCode> statusCodes = null;
        try {
            statusCodes = listCompletableFuture.get();
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (StatusCode t : statusCodes) {
            log.error("批量-写数据：{}，耗时：{}", t.toString(), System.currentTimeMillis() - x);
        }
    }

}
